package com.chenyuhan.myview.testview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

import com.chenyuhan.myview.R;

/**
 * Created by Administrator on 2017/6/30 0030.
 */

public class TestCardView extends ViewGroup {
    private final String TAG = TestCardView.class.getSimpleName();
    /**
     * 阴影高度
     */
    private int cardElevation = 0;
    /**
     * 底边和侧边阴影高度
     */
    private int bottomCardElevation = 0;
    private int sideCardElevation = 0;

    /**
     * 排列方向
     */
    private int orientation = HORIZONTAL;

    /**
     * 圆角半径
     */
    private int cardCornerRadius = 0;
    public static final int HORIZONTAL = 0;
    public static final int VERTICAL = 1;

    /**
     * 阴影画笔
     */
    private Paint mPaint;

    public TestCardView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TestCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //不设置的话自定义viewGroup不会调用onDraw()方法（或者设置背景）
        setWillNotDraw(false);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TestCardView, defStyleAttr, 0);
        for (int i = 0; i < typedArray.getIndexCount(); i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.TestCardView_cardElevation:
                    cardElevation = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
                    bottomCardElevation = cardElevation;
                    sideCardElevation = cardElevation / 2;
                    break;
                case R.styleable.TestCardView_android_orientation:
                    orientation = typedArray.getInt(attr, HORIZONTAL);//默认为横向
                    break;
                case R.styleable.TestCardView_cardCornerRadius:
                    cardCornerRadius = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics()));
                    break;
            }
        }
        typedArray.recycle();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);//设置空心
        mPaint.setColor(bgColor);//设置颜色
        // 第一个参数为模糊半径，越大越模糊。 第二个参数是阴影离开文字的x横向距离。 第三个参数是阴影离开文字的Y横向距离。 第四个参数是阴影颜色。
        mPaint.setShadowLayer(10, sideCardElevation, bottomCardElevation, Color.GRAY);
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        int count = getChildCount();
        //累加的宽高
        int aWidth = 0;
        int aHeight = 0;
        if (orientation == VERTICAL) {
            for (int y = 0; y < count; y++) {
                View child = getChildAt(y);
                if (child.getVisibility() != GONE) {
                    int viewWidth = child.getMeasuredWidth();
                    int viewHeight = child.getMeasuredHeight();
                    MarginLayoutParams st = (MarginLayoutParams) child.getLayoutParams();
                    child.layout(aWidth + st.leftMargin + bottomCardElevation, aHeight + st.topMargin + bottomCardElevation, aWidth + viewWidth + st.rightMargin, aHeight + viewHeight + st.bottomMargin);
                    //因为是竖向布局,所以将当前高度累加起来
                    aHeight += viewHeight + st.topMargin + st.bottomMargin;
                }
            }
        } else {
            for (int y = 0; y < count; y++) {
                View child = getChildAt(y);
                if (child.getVisibility() != GONE) {
                    int viewWidth = child.getMeasuredWidth();
                    int viewHeight = child.getMeasuredHeight();
                    MarginLayoutParams st = (MarginLayoutParams) child.getLayoutParams();
                    child.layout(aWidth + st.leftMargin + bottomCardElevation, aHeight + st.topMargin + bottomCardElevation, aWidth + viewWidth + st.rightMargin, aHeight + viewHeight + st.bottomMargin);
                    //因为是竖向布局,所以将当前高度累加起来
                    aWidth += viewWidth + st.leftMargin + st.rightMargin;
                }
            }
        }
    }

    /**
     * 重写父类的该方法，返回MarginLayoutParams的实例，这样就为我们的ViewGroup指定了其LayoutParams为MarginLayoutParams(支持margin的LayoutParams)。
     *
     * @param attrs
     * @return
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /**
         * 获得此ViewGroup上级容器为其推荐的宽和高，以及计算模式
         */
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        // 计算出所有的childView的宽和高
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        //总宽高
        int aWidth = 0;
        int aHeight = 0;
        //子控件数量
        int childCount = getChildCount();
        //根据排列方向计算所有子控件的宽高总和
        if (orientation == VERTICAL) {
            //竖向布局
            for (int i = 0; i < childCount; i++) {
                //获得childView的宽高和MarginLayoutParams
                View childView = getChildAt(i);
                int childViewWidth = childView.getMeasuredWidth();
                int childViewHeight = childView.getMeasuredHeight();
                MarginLayoutParams childViewParams = (MarginLayoutParams) childView.getLayoutParams();

                //高为所有控件高之和
                aHeight += childViewHeight + childViewParams.topMargin + childViewParams.bottomMargin;
                //宽为所有控件中宽的最大值
                aWidth = Math.max(aWidth, childViewWidth);
            }
        } else {
            for (int i = 0; i < childCount; i++) {
                //获得childView的宽高和MarginLayoutParams
                View childView = getChildAt(i);
                int childViewWidth = childView.getMeasuredWidth();
                int childViewHeight = childView.getMeasuredHeight();
                MarginLayoutParams childViewParams = (MarginLayoutParams) childView.getLayoutParams();

                //宽为所有控件宽之和
                aWidth += childViewWidth + childViewParams.leftMargin + childViewParams.rightMargin;
                //高为所有控件中高的最大值
                aHeight = Math.max(aHeight, childViewHeight);
            }
        }
        if (widthMode == MeasureSpec.EXACTLY)
            aWidth = sizeWidth;

        if (heightMode == MeasureSpec.EXACTLY)
            aHeight = sizeHeight;

        //加上阴影的宽高(上下左右，所以*2)
        aWidth += 2 * sideCardElevation;
        aHeight += 2 * bottomCardElevation;
        /**
         * 如果是wrap_content设置为我们计算的值
         * 否则：直接设置为父容器计算的值
         */
        setMeasuredDimension(aWidth, aHeight);
    }

    /**
     * 背景颜色
     *
     * @param
     */
    private int bgColor = Color.WHITE;

    @Override
    protected void onDraw(Canvas canvas) {
        disableHardwareRendering(this);
        //获得设定的背景或者颜色
        Drawable background = getBackground();
        if (background != null) {
            //background包括color和Drawable,这里分开取值
            if (background instanceof ColorDrawable) {
                ColorDrawable colordDrawable = (ColorDrawable) background;
                int color = colordDrawable.getColor();
                bgColor = color;
            } else {
                Bitmap bgBitmap = ((BitmapDrawable) background).getBitmap();
                return;
            }
        }
        //画非阴影区域的长方形
        RectF rectF = new RectF(sideCardElevation, bottomCardElevation, getMeasuredWidth() - sideCardElevation, getMeasuredHeight() - bottomCardElevation);
        canvas.drawRoundRect(rectF, cardCornerRadius, cardCornerRadius, mPaint);
    }

    //关闭硬件加速，防止设置阴影没效果
    public static void disableHardwareRendering(View v) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            v.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }

}
